package com.dyzx.hbb.modules.fcxs.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.common.utils.DateFormat;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.fcxs.entity.FcxsClue;
import com.dyzx.hbb.modules.fcxs.entity.FcxsOrder;
import com.dyzx.hbb.modules.fcxs.entity.FcxsVisit;
import com.dyzx.hbb.modules.fcxs.query.FcxsClueQuery;
import com.dyzx.hbb.modules.fcxs.service.FcxsClueService;
import com.dyzx.hbb.modules.fcxs.service.FcxsVisitService;
import com.dyzx.hbb.modules.fcxs.vo.FcxsClueVO;
import com.dyzx.hbb.modules.fcxs.vo.FcxsClueUVO;
import com.dyzx.hbb.common.controller.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 线索管理控制器
 * 
 * 功能说明：负责处理房地产销售系统中潜在客户线索的创建、查询、更新和删除等操作
 * 主要职责：
 * - 提供客户线索的CRUD接口
 * - 支持按条件查询线索列表
 * - 关联拜访计划信息进行综合管理
 * - 支持按客户名称、联系方式、状态等条件筛选线索数据
 * - 处理线索的状态变更和跟进管理
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "02.线索管理", description = "线索管理相关接口")
@RestController
@RequestMapping("/fcxs/clue")
public class FcxsClueController extends BaseValidController<
        FcxsClueService,
        FcxsClue,
        FcxsClueQuery,
        FcxsClueVO,
        FcxsClueUVO
        > {
    @Autowired
    private FcxsClueService fcxsClueService;

    @Autowired
    private FcxsVisitService fcxsVisitService;

    /**
     * 获取基础服务层实例
     * 
     * @return FcxsClueService 线索服务层实例
     */
    @Override
    protected FcxsClueService getBaseService() {
        return fcxsClueService;
    }

    /**
     * 构建线索查询条件
     * 
     * @param query 线索查询参数
     * @return MyLambdaQueryWrapper<FcxsClue> 查询条件包装器
     */
    @Override
    protected MyLambdaQueryWrapper<FcxsClue> queryWrapper(FcxsClueQuery query) {
        MyLambdaQueryWrapper<FcxsClue> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsClue::getId)
                .select(FcxsClue::getClueNo)
                .select(FcxsClue::getName)
                .select(FcxsClue::getPhone)
                .select(FcxsClue::getCustomerNeeds)
                .select(FcxsClue::getCustomerSuggestions)
                .select(FcxsClue::getCfmName)
                .select(FcxsClue::getCfmPhone1)
                .select(FcxsClue::getCfmPhone2)
                .select(FcxsClue::getCfmCustomerNeeds)
                .select(FcxsClue::getAge)
                .select(FcxsClue::getSex)
                .select(FcxsClue::getOccupation)
                .select(FcxsClue::getLevel)
                .select(FcxsClue::getCfmDate)
                .select(FcxsClue::getStatus)
                .select(FcxsClue::getCreateDate)
                .select(FcxsClue::getUpdateDate)
                .organName(FcxsClue::getOrganId).as("organ_name")
                .userName(FcxsClue::getOperatorId).as("operator_name")
                .select("IFNULL((SELECT  (CASE WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) * 1000 THEN 1 WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 3 MONTH)) * 1000 THEN 3 ELSE 4 END) FROM fcxs_visit WHERE deleted = 0 and clue_id=fcxs_clue.id and type=1 ORDER BY ID DESC LIMIT 1),4)").as("visit_status")
                .select("IFNULL((SELECT  (CASE WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) * 1000 THEN 1 WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 3 MONTH)) * 1000 THEN 3 ELSE 4 END) FROM fcxs_visit WHERE deleted = 0 and clue_id=fcxs_clue.id and type=2 ORDER BY ID DESC LIMIT 1),4)").as("visit_arrival");

        if (query != null) {
            queryWrapper.eq(StringUtils.isNotBlank(query.getOccupation()), FcxsClue::getOccupation, query.getOccupation())
                    .dateBetween(StringUtils.isNotBlank(query.getCreate_date()), FcxsClue::getCreateDate, DateFormat.DATE, query.getCreate_date())
                    .findInSet(StringUtils.isNotBlank(query.getLevel()), FcxsClue::getLevel, query.getLevel())
                    .findInSet(StringUtils.isNotBlank(query.getStatus()), FcxsClue::getStatus, query.getStatus());
        }
        return queryWrapper;
    }

    /**
     * 构建线索详情查询条件
     * 
     * @return MyLambdaQueryWrapper<FcxsClue> 查询条件包装器
     */
    @Override
    protected MyLambdaQueryWrapper<FcxsClue> queryInfoWrapper() {
        MyLambdaQueryWrapper<FcxsClue> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsClue::getId)
                .select(FcxsClue::getName)
                .select(FcxsClue::getPhone)
                .select(FcxsClue::getCustomerNeeds)
                .select(FcxsClue::getCustomerSuggestions)
                .select(FcxsClue::getCfmName)
                .select(FcxsClue::getCfmPhone1)
                .select(FcxsClue::getCfmPhone2)
                .select(FcxsClue::getCfmCustomerNeeds)
                .select(FcxsClue::getAge)
                .select(FcxsClue::getSex)
                .select(FcxsClue::getOccupation)
                .select(FcxsClue::getLevel)
                .select(FcxsClue::getCfmDate)
                .select(FcxsClue::getStatus)
                .select(FcxsClue::getCreateDate)
                .select(FcxsClue::getUpdateDate)
                .organName(FcxsClue::getOrganId).as("organ_name")
                .userName(FcxsClue::getOperatorId).as("operator_name")
                .select("IFNULL((SELECT  (CASE WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) * 1000 THEN 1 WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 3 MONTH)) * 1000 THEN 3 ELSE 4 END) FROM fcxs_visit WHERE deleted = 0 and clue_id=fcxs_clue.id and type=1 ORDER BY ID DESC LIMIT 1),4)").as("visit_status")
                .select("IFNULL((SELECT  (CASE WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) * 1000 THEN 1 WHEN create_date >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 3 MONTH)) * 1000 THEN 3 ELSE 4 END) FROM fcxs_visit WHERE deleted = 0 and clue_id=fcxs_clue.id and type=2 ORDER BY ID DESC LIMIT 1),4)").as("visit_arrival");

        return queryWrapper;
    }

    /**
     * 验证并处理新增线索数据
     * 
     * @param entity 线索新增参数
     * @return FcxsClue 处理后的线索实体
     */
    @Override
    protected FcxsClue addValid(FcxsClueVO entity) {
        FcxsClue data = new FcxsClue();
        BeanUtil.copyProperties(entity, data);
        String s = Utils.generateYyMMOrderNumber("XS");
        data.setClueNo(s);
        return data;
    }

    /**
     * 验证并处理编辑线索数据
     * 
     * @param entity 线索编辑参数
     * @return FcxsClue 处理后的线索实体（当前返回null）
     */
    @Override
    protected FcxsClue editValid(FcxsClueUVO entity) {
        return null;
    }

    /**
     * 根据ID查询线索详情
     * @param id 线索ID
     * @return 线索详情信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询线索详情", description = "根据ID查询线索的详细信息")
    public Result<Map<String, Object>> getById(@Parameter(description = "线索ID") @PathVariable Long id) {
        MyLambdaQueryWrapper<FcxsClue> queryWrapper = queryInfoWrapper();
        queryWrapper.select(FcxsClue::getCreateDate, FcxsClue::getUpdateDate);

        queryWrapper.eq(FcxsClue::getId, id);
        queryWrapper.last("limit 1");
        Map<String, Object> data = getBaseService().getMap(queryWrapper);
        if (data == null) {
            return Result.error("未查询到数据");
        }
        MyLambdaQueryWrapper<FcxsVisit> fcxsVisitMyLambdaQueryWrapper = queryInfoVisitWrapper();
        List<Map<String, Object>> visitData = fcxsVisitService.listMaps(fcxsVisitMyLambdaQueryWrapper.eq(FcxsVisit::getClueId, id));
        data.put("visit", visitData);

        return Result.ok(data);
    }

    /**
     * 构建线索回访记录查询条件
     * 
     * @return MyLambdaQueryWrapper<FcxsVisit> 回访记录查询条件包装器
     */
    protected MyLambdaQueryWrapper<FcxsVisit> queryInfoVisitWrapper() {
        MyLambdaQueryWrapper<FcxsVisit> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsVisit::getId)
                .select(FcxsVisit::getClueId)
                .fcxsClueNo(FcxsVisit::getClueId).as("clue_no")
                .select(FcxsVisit::getType)
                .select(FcxsVisit::getStatus)
                .select(FcxsVisit::getRemark)
                .select(FcxsVisit::getCreateDate)
                .select(FcxsVisit::getUpdateDate)
                .organName(FcxsVisit::getOrganId).as("organ_name")
                .userName(FcxsVisit::getOperatorId).as("operator_name");
        return queryWrapper;
    }
}
